package cn.yunhe.control;

import cn.yunhe.entity.Myfriend;
import cn.yunhe.entity.User;
import cn.yunhe.server.FriendServer;
import cn.yunhe.server.UserServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/AddFriendServlet")
public class AddFriendServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String uName = request.getParameter("uName");
        String username = (String) session.getAttribute("username");
        //调用server层对象
        UserServer userServer = new UserServer();
        FriendServer friendServer = new FriendServer();

        boolean flag = userServer.checkUserName(uName);
        if (flag){
            List<User> userList = userServer.getUser(username); //通用户名查询用户全部信息
            List<User> friendList = userServer.getUser(uName);  //通过用户名获取好友信息
            //获取用户信息和好友信息
            int uId = userList.get(0).getuId();
            String userName = userList.get(0).getuName();
            int fuId = friendList.get(0).getuId();
            String fuName = friendList.get(0).getuName();

            Myfriend myfriend = new Myfriend(uId,userName,fuId,fuName);
            boolean b = friendServer.AddFriend(myfriend);
            if (b){
                request.setAttribute("result","好友添加消息已经发送,请等待回复!!");
                request.getRequestDispatcher("addFrend.jsp").forward(request,response);
            }else {
                request.setAttribute("result","好友添加失败!!");
                request.getRequestDispatcher("addFrend.jsp").forward(request,response);
            }
        }else {
            request.setAttribute("result","该用户名不存在!!");
            request.getRequestDispatcher("addFrend.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
